import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;

import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class FreemarkerPOIDemo {
    public static void main(String[] args) throws IOException, TemplateException {
        // 准备Freemarker环境
        Configuration cfg = new Configuration(Configuration.VERSION_2_3_30);
        cfg.setDirectoryForTemplateLoading(new File("path/to/templates"));

        // 加载模板
        Template template = cfg.getTemplate("template.ftl");

        // 准备数据模型
        Map<String, Object> dataModel = new HashMap<>();
        dataModel.put("title", "Hello World!");
        dataModel.put("content", "This is the content of the document.");

        // 解析模板并生成HTML/XML
        StringWriter stringWriter = new StringWriter();
        template.process(dataModel, stringWriter);

        // 使用Apache POI读取Word模板
        FileInputStream fis = new FileInputStream("path/to/template.docx");
        XWPFDocument doc = new XWPFDocument(fis);

        // 替换占位符
        for (XWPFParagraph p : doc.getParagraphs()) {
            List<XWPFRun> runs = p.getRuns();
            if (runs != null) {
                for (XWPFRun r : runs) {
                    String text = r.getText(0);
                    if (text != null && text.contains("${")) {
                        text = stringWriter.toString().replaceAll("\\$\\{.*?\\}", "");
                        r.setText(text, 0);
                    }
                }
            }
        }

        // 保存文档
        FileOutputStream out = new FileOutputStream("output.docx");
        doc.write(out);
        out.close();
        doc.close();
        fis.close();
    }
}